//引用接口
import { login, getUserInfo, getUserDetailInfo } from '@/api/user'
//引入持久化缓存
import { getToken, setToken, removeToken, setTime } from '@/utils/auth'
export default {
    namespaced: true,
    state: {
        token: getToken(), //token
        userInfo: {}, //用户信息
    },
    mutations: {
        //设置token
        setToken(state, data) {
            state.token = data
            setToken(data)
                //这里设置token了，就记录登录时间
            setTime()
        },
        //删除token
        removeToken(state) {
            state.token = null
            removeToken()
        },
        //设置用户信息
        setUserInfo(state, data) {
            state.userInfo = data
        },
        // 删除用户资料
        removeUserInfo(state) {
            state.userInfo = {}
        }
    },
    actions: {
        //异步修改   登录
        async actionsLogin(context, data) {
            console.log(context, '-------------context');
            console.log(data, '------------data');
            const res = await login(data)
            console.log(res); //现在这个res就是token
            context.commit('setToken', res)
        },
        //获取用户信息
        async actionsUserInfo(context) {
            const res = await getUserInfo()
            const res2 = await getUserDetailInfo(res.userId)
            console.log(res);
            console.log(res2);
            //用拓展运算符拼接对象都存到userInfo里
            context.commit('setUserInfo', {...res, ...res2 })
        },
        //退出登录
        logout(context) {
            //删除用户信息 和token
            context.commit('removeUserInfo')
            context.commit('removeToken')
        }
    }
}